#include 	"hal_motor.h"
#include	"STC8G_H_GPIO.h"
#include	"STC8G_H_Delay.h"
#include    "STC8G_H_UART.h"
#include	"STC8G_H_NVIC.h"
#include 	"STC8G_H_Switch.h"
#include 	"STC8H_PWM.h"

#define PERIOD (MAIN_Fosc / 1000)
#define ENGINE_GPIO_PORT GPIO_P0
#define ENGINE_GPIO_PIN GPIO_Pin_1

static void GPIO_config(void) {

	GPIO_InitTypeDef	GPIO_InitStructure;		//结构定义
    // P01 震动马达
	GPIO_InitStructure.Pin  = ENGINE_GPIO_PIN;		//指定要初始化的IO,
    // 推挽输出
	GPIO_InitStructure.Mode = GPIO_OUT_PP;	//指定IO的输入或输出方式,GPIO_PullUp,GPIO_HighZ,GPIO_OUT_OD,GPIO_OUT_PP
	GPIO_Inilize(ENGINE_GPIO_PORT, &GPIO_InitStructure);//初始化

}

static void	PWM_config(void)
{
	PWMx_InitDefine		PWMx_InitStructure;
	
	// 配置PWM6
	PWMx_InitStructure.PWM_Mode    		= CCMRn_PWM_MODE1;	//模式,		CCMRn_FREEZE,CCMRn_MATCH_VALID,CCMRn_MATCH_INVALID,CCMRn_ROLLOVER,CCMRn_FORCE_INVALID,CCMRn_FORCE_VALID,CCMRn_PWM_MODE1,CCMRn_PWM_MODE2
	PWMx_InitStructure.PWM_Duty    		= 0.0 * PERIOD;	//PWM占空比时间, 0~Period
	PWMx_InitStructure.PWM_EnoSelect    = ENO6P;			//输出通道选择,	ENO1P,ENO1N,ENO2P,ENO2N,ENO3P,ENO3N,ENO4P,ENO4N / ENO5P,ENO6P,ENO7P,ENO8P
	PWM_Configuration(PWM6, &PWMx_InitStructure);			//初始化PWM,  PWMA,PWMB

	// 配置PWMB
	PWMx_InitStructure.PWM_Period   = PERIOD - 1;			//周期时间,   0~65535
	PWMx_InitStructure.PWM_DeadTime = 0;					//死区发生器设置, 0~255
	PWMx_InitStructure.PWM_MainOutEnable= ENABLE;			//主输出使能, ENABLE,DISABLE
	PWMx_InitStructure.PWM_CEN_Enable   = ENABLE;			//使能计数器, ENABLE,DISABLE
	PWM_Configuration(PWMB, &PWMx_InitStructure);			//初始化PWM通用寄存器,  PWMA,PWMB

	// 切换PWM通道
	PWM6_SW(PWM6_SW_P01);					//PWM6_SW_P21,PWM6_SW_P54,PWM6_SW_P01,PWM6_SW_P75

	// 初始化PWMB的中断
	NVIC_PWM_Init(PWMB,DISABLE,Priority_0);
}

void HAL_MOTOR_Init(){

    EA = 1; // 使能全局中断
    EAXSFR();		
    GPIO_config();
    PWM_config();

}

void HAL_MOTOR_SetSpeed(float speed){
    PWMx_Duty duty;
    duty.PWM6_Duty = (speed / 100.0) * PERIOD; 
    UpdatePwm(PWMB, &duty);
}